package org.feidao.chapter72;

import com.feidao.service.User;
import com.feidao.service.UserService;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import java.util.List;

//thrift client service的管理
public class UserServiceManager {
    //thrift service端口
    public final static int SERVER_USER_PORT = 8888;
    //延时
    public final static int SERVER_TIME_DELAY = 30000;
    //server host
    private String host = "localhost";

    private TTransport tTransport = null;
    private UserService.Client client;

    public UserServiceManager(){

        try {
            tTransport = new TSocket(host,SERVER_USER_PORT,SERVER_TIME_DELAY);

            //定义协议
            TProtocol tProtocol = new TBinaryProtocol(tTransport);
            //创建client
            client = new UserService.Client(tProtocol);
            //打开通道
            tTransport.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void destroy(){
        if(tTransport!=null){
            tTransport.close();
        }
    }

    //测试与server端的通信
    public void testCommunication(){
        System.out.println("send ping....");
        try {
            String str = client.ping();
            if(!str.isEmpty()){
                System.out.println("receive:" + str);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void getService(){
        try {
            List<User> userList = client.getUserList();
            if(userList!=null&& userList.size()>0){
                for(int i=0;i< userList.size();i++){
                    User user = userList.get(i);
                    System.out.println("user:" + user.userName);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
